package com.sinba.itsm.bugfix;

import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;

import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class RequestWrapper
    extends HttpServletRequestWrapper
{
    public RequestWrapper( HttpServletRequest request )
    {
        super( request );
    }

    @SuppressWarnings( {"rawtypes",
        "unchecked"
    } )
    public Map<String, String[]> getParameterMap(  )
    {
        Map<String, String[]> request_map = super.getParameterMap(  );
        Iterator iterator = request_map.entrySet(  ).iterator(  );

        while ( iterator.hasNext(  ) )
        {
            Map.Entry me = (Map.Entry) iterator.next(  );

            //System.out.println(me.getKey()+":");
            String[] values = (String[]) me.getValue(  );

            for ( int i = 0; i < values.length; i++ )
            {
                values[i] = xssClean( values[i] );
            }
        }

        return request_map;
    }

    private String xssClean( String value )
    {
        AntiSamy antiSamy = new AntiSamy(  );

        try
        {
            InputStream inputStream = this.getClass(  ).getClassLoader(  ).getResourceAsStream( "xssRule.xml" );
            Policy policy = Policy.getInstance( inputStream );

            //CleanResults cr = antiSamy.scan(dirtyInput, policyFilePath); 
            final CleanResults cr = antiSamy.scan( value, policy );

            //安全的HTML输出
            return cr.getCleanHTML(  );
        } catch ( ScanException e )
        {
            e.printStackTrace(  );
        } catch ( PolicyException e )
        {
            e.printStackTrace(  );
        }

        return value;
    }
}
